package com.zwj.gateway.filter;

import com.zwj.gateway.config.AuthProperties;
import com.zwj.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 登录校验过滤器
 *
 * @author 张文接
 * @version 1.0
 * @createTime 2024/7/21 15:16
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AuthGlobalFilter implements GlobalFilter, Ordered {
    /**
     * jwt工具类
     */
    private final JwtTool jwtTool;
    /**
     * 需要/不需要登录验证的请求path
     */
    private final AuthProperties authProperties;
    /**
     * 请求Path解析匹配工具类
     */
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求request
        ServerHttpRequest request = exchange.getRequest();
        //判断是否需要拦截
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        //获取请求头
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollectionUtils.isEmpty(headers)) {
            token = headers.get(0);
        }
        //解析token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            //响应
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //讲用户id塞到请求头里
        ServerWebExchange serverWebExchange = exchange
                .mutate()
                .request(r -> r.header("user-info", userId.toString()))
                .build();
        return chain.filter(serverWebExchange);
    }

    /**
     * 判断path是否包含在内
     *
     * @param path 请求path
     * @return 包含：true，不包含：false
     */
    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
